// Import System requirements
import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
import routes from './routes';
import store from './store';
import vueMoment from 'vue-moment';
import 'moment/locale/zh-cn';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import filters from './filters';
import app from './App.vue';
import { isNoAuth } from '__service/utils';
import tzVueUI from './components/icon-file-type';
import 'tz-vue-ui/dist/static/css/tz-vue-ui.css';
import { api } from './views/login/api';
import localStorage from 'localStorage';
import { LOCAL_USER } from './store/user';
import csConst from './store/csConst';

// 注册文件icon组件
Vue.component('tz-icon-file-type', tzVueUI);

// 注册过滤器
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key]);
});
// Resource logic
Vue.use(VueRouter);
Vue.use(ElementUI);
// 注册moment
Vue.use(vueMoment);

window.$Vue = Vue;

// 注册全局判断权限方法
Vue.prototype.isNoAuth = isNoAuth;
let baseURL = '';

/*global process:true*/
/*eslint no-undef: "error"*/
if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
    baseURL = 'http://192.168.2.239:3329';
} else {
    baseURL = 'http://183.62.147.106:81';
}

// 凯斯重构版
Vue.prototype.baseURL = axios.defaults.baseURL = baseURL + '/refactoring';
Vue.prototype.basePreviewURL = baseURL;
// 判断是 母基金还是直投
Vue.prototype.FOF = csConst.state.FOF;
//添加拦截器注入 token
axios.interceptors.request.use(function (config) {
    if (config.url.indexOf(api.API_LOGIN.url) === -1 && store.state.user.token) {
        config.headers['X-Token'] = store.state.user.token.toString();
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

// Routing logic
const router = new VueRouter({
    routes: routes,
    mode: process.env.NODE_ENV === 'development' ? 'history' : 'hash',
    scrollBehavior: function (to, from, savedPosition) {
        return savedPosition || {
                x: 0,
                y: 0
            };
    }
});
window.$router = router;
let isNewWindow = false;
let myTime = null;
router.beforeEach((to, from, next) => {
    window.scrollTo(0, 0);
    if (from.path === '/') {
        isNewWindow = true;
    } else {
        isNewWindow = false;
    }
    if (to.name === 'login' || to.path === '/login') {
        store.dispatch('singOut');
        clearInterval(myTime);
        next();
        return;
    } else {
        //查找 token
        if (to.meta.auth === true && store.state.user.token) {
            //判定内存和local 是否一致 不一直说明,登录了新用户,强制登出
             if (!isLocalStorageUser()) {
                     next({
                         path: 'login'
                     });
             }
            if (to.params.openWindow && process.env.NODE_ENV !== 'development') {
                let openUrl = to.fullPath;
                if (router.mode === 'hash') {
                    openUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + '#' + to.fullPath;
                }
                // console.log(openUrl);
                window.open(openUrl, '_blank');
            } else {
                next();
            }
        } else {
            store.dispatch('refreshUser').then(
                retUser => {
                    if (retUser === null) {
                        next({
                            path: 'login'
                        });
                    } else {
                        store.commit('SIGN_IN', retUser);
                        store.dispatch('getMsg');
                        store.dispatch('refreshFieldList').then(() => { // 获取menu小红点
                                // 一分钟后未读消息重新轮循
                                if (process.env.NODE_ENV !== 'development') {
                                    myTime = setInterval(() => {
                                        store.commit('SIGN_IN', retUser);
                                        store.dispatch('getMsg'); // 获取menu小红点
                                        store.dispatch('refreshFieldList'); // 更新字典等信息
                                    }, 60000);
                                }
                                next();
                            });
                    }
                },
                () => {
                    next({
                        name: 'login'
                    });
                }
            );
        }
    }
});
// 表头换行
Vue.prototype.renderTitle = (h, { column }) => {
    let textList = [];
    let brIndex = column.label.indexOf('</br>');
    if (brIndex !== -1) {
        textList.push({name: 'span', text: column.label.substr(0, brIndex)});
        textList.push({name: 'br', text: ''});
        textList.push({name: 'span', text: column.label.substr(brIndex + 5, column.label.length)});
    }
    textList = textList.map(item => {
        return h(item.name, item.text)
    });
    return textList;
};
// 分页
Vue.prototype.vuePageSizes = [30, 60, 90];
Vue.prototype.vuePageSize = 30;
// 验证金额 小数点前10后6
Vue.prototype.validateMoneyNumber = (rule, value, callback) => {
    var reg = /^\d{1,10}(\.\d{1,6})?$/;
    if (value && (!reg.test(value))) {
        callback(new Error('请输入正确范围的数字'));
    } else {
        callback();
    }
}
// 投资期 退出期 只能输入正整数
Vue.prototype.checkIntegerNumber = (rule, value, callback) => {
    let reg = /^[1-9]\d*$/;
    if (!reg.test(value)) {
        callback(new Error('请输入正整数'));
    } else {
        callback();
    }
};

var appVue = new Vue({
    el: '#root',
    data: function () {
        return {
            Dot: new Vue()
        };
    },
    methods: {
    },
    router,
    store,
    render: h => h(app)
}).
    //系统异常
    $on('netError', function (msg = '系统异常') {
        // console.log(msg);
        this.$message.error(msg);
    })
    // 用户禁用
    .$on('goToLogin', function (msg = '该用户被禁用!') {
        this.$message.error(msg);
        if (process.env.NODE_ENV !== 'development' && isNewWindow) {
            window.location.href = 'about:blank';
            window.close();
        } else {
            this.$router.replace({
                name: 'login'
            });
        }
    })

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    let msg = '';
    if (response.status === 200 && response.data.resCode && response.data.resCode !== '0') {
        let errorType = 'netError';
        if (response.data.resCode === '-17') { // 用户被禁用
            msg = response.data.resMsg;
            errorType = 'goToLogin';
        } else if (response.data.resCode === '-13') { // 用户未登陆
            msg = response.data.resMsg;
            errorType = 'goToLogin';
        } else {
            msg = response.data.resMsg;
        }
        appVue.$emit(errorType, msg);
    }
    return response;
}, function (error) {
    return Promise.reject(error);
});
// 判定内存和local 是否一致
function isLocalStorageUser() {
    let user = localStorage.getItem(LOCAL_USER);
    return user === null ? true : (store.state.user.token === JSON.parse(user).token);
}
